package history.hot100;

import java.util.LinkedList;

// 394. 字符串解码:https://leetcode-cn.com/problems/decode-string/
// https://leetcode-cn.com/problems/decode-string/solution/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/
public class LeetCode_394 {
    public String decodeString(String s) {
        StringBuffer ret = new StringBuffer();
        int multi = 0;
        LinkedList<Integer> stack_multi = new LinkedList<>();
        LinkedList<String> stack_ret = new LinkedList<>();
        for (Character c: s.toCharArray()) {
            if (c == '[') {
                stack_multi.addLast(multi);
                stack_ret.addLast(ret.toString());
                multi = 0;
                ret =  new StringBuffer();
            }else if (c == ']') {
                StringBuffer tmp = new StringBuffer();
                int cur_multi = stack_multi.removeLast();
                for (int i = 0; i < cur_multi; i++) tmp.append(ret);
                ret = new StringBuffer(stack_ret.removeLast()+tmp);
            } else if (c>='0'&& c<='9') multi = multi*10+Integer.parseInt(c+"");
            else ret.append(c);
        }
        return ret.toString();
    }
}
